'use strict';

const Controller = require('egg').Controller;
const axios = require('axios');
const fs = require('mz/fs');
const path = require('path');
const pump = require('mz-modules/pump');

class HomeController extends Controller {
  async index () {
    const { ctx } = this;
    ctx.body = 'hi, egg';
  }

  async menu () {
    const { ctx } = this;
    ctx.status = 201;
    ctx.body = { code: 20000 };
  }

  async readUrl () {
    const { ctx } = this;
    const url = ctx.query.url;
    // 设置响应内容和响应状态码
    await axios.get(url).then(response => {
      // console.debug('...接收url....', url)
      console.debug(response.data);
      ctx.status = 200;
      ctx.body = response.data;
    });
  }

  async upload () {
    const { ctx, config } = this;
    const stream = await ctx.getFileStream();
    // const filename = encodeURIComponent(stream.fields.name) + path.extname(stream.filename).toLowerCase()

    const filename = path.extname(stream.filename).toLocaleUpperCase().substr(1) + Math.random().toString(8).substr(2, 6) + path.extname(stream.filename).toLowerCase();
    const tempPath = (new Date()).getTime() + Math.random().toString(36).substr(2) + '/'; // path.extname(file.filename).toLocaleLowerCase();

    // const uploadPath = path.join(config.baseDir, 'app/public/upload/')
    const uploadPath = path.join(config.baseDir, 'uploadFiles', 'upload');

    if (!fs.existsSync(uploadPath)) {
      fs.mkdir(uploadPath, { recursive: true }, err => {
        if (err !== null) {
          console.error('...........新建文件夹失败......[', uploadPath, ']....', err);
          throw new Error('创建UPLOAD目录失败!');
        }
      });
    }
    const target = path.join(config.baseDir, 'uploadFiles', 'upload', tempPath);
    if (!fs.existsSync(target)) {
      fs.mkdir(target, { recursive: true }, err => {
        if (err !== null) {
          console.error('...........新建文件夹失败......[', target, ']....', err);
          throw new Error('创建目录失败!');
        }
      });
    }
    console.debug('............上传文件是..名称:', filename, '..............路径...........', target);
    const writeStream = fs.createWriteStream(target + filename);
    await pump(stream, writeStream);

    ctx.body = { code: 20000, data: { name: filename, url: tempPath + filename }, url: tempPath + filename };
  }
}

module.exports = HomeController;
